package dao

import (
	"context"
	"errors"
	"gin/webook/internal/web/validate"
	"github.com/go-sql-driver/mysql"
	"gorm.io/gorm"
	"time"
)

var (
	ErrDuplicateEmail = errors.New("邮箱已存在")
	ErrRecordNotFound = gorm.ErrRecordNotFound
)

type UserDao struct {
	db *gorm.DB
}

func NewUserDao(db *gorm.DB) *UserDao {
	return &UserDao{db: db}
}

func (dao *UserDao) Insert(ctx context.Context, u User) error {
	now := time.Now().UnixMilli()
	u.CreateTime = now
	u.UpdateTime = now
	err := dao.db.WithContext(ctx).Create(&u).Error
	if me, ok := err.(*mysql.MySQLError); ok {
		const duplicateErr uint16 = 1062
		if me.Number == duplicateErr {
			//邮箱已存在
			return ErrDuplicateEmail
		}
	}
	return err
}

func (dao *UserDao) FindByEmail(ctx context.Context, email string) (User, error) {

	var u User
	err := dao.db.WithContext(ctx).Where("email=?", email).First(&u).Error
	return u, err
}

func (dao *UserDao) FindByUid(ctx context.Context, uid int64) (User, error) {

	var u User
	err := dao.db.WithContext(ctx).Where("id=?", uid).First(&u).Error
	return u, err
}

func (dao *UserDao) UpdateUserInfoByUid(ctx context.Context, uid int64, req validate.ProfileReq) (User, error) {
	var u User
	dt, err := time.Parse("2006-01-02", req.Birth)
	if err != nil {
		return User{}, err
	}

	u.Id = uid
	err = dao.db.WithContext(ctx).Model(&u).Updates(
		User{
			NickName:     req.NickName,
			Birth:        dt.Unix(),
			Introduction: req.Introduction,
		}).Error
	return u, err
}

type User struct {
	Id           int64  `gorm:"primaryKey,autoIncrement"`
	Email        string `gorm:"unique"`
	Password     string
	NickName     string
	Birth        int64
	Introduction string
	CreateTime   int64
	UpdateTime   int64
}
